package cn.jietuo.first.class02;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/6/18
 * @description: 数组实现栈和队列
 * 其中使用环形数组实现队列
 */
public class Code04_RingArray {

    /**
     * 定长数组实现队列
     */
    public static class MyQueue {

        /** 拿数据指针index */
        private int pollIndex;

        /** 放入数据指针index */
        private int putIndex;

        /** 数组大小 */
        private int size;

        /** 最大长度限制 */
        private final int limit;

        private int[] array;

        public MyQueue(int limit) {
            putIndex = 0;
            pollIndex = 0;
            size = 0;
            this.limit = limit;
            array = new int[limit];
        }

        public void push(int value) {
            if (size == limit) {
                throw new RuntimeException("队列已经装满了。。。");
            }
            size++;
            array[putIndex] = value;
            putIndex = nextIndex(putIndex);
        }

        public int poll() {
            if (size == 0) {
                throw new RuntimeException("队列中没有数据了。。。");
            }
            size--;
            int value = array[pollIndex];
            pollIndex = nextIndex(pollIndex);
            return value;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        private int nextIndex(int index) {
            return index < limit - 1 ? index++ : 0;
        }

        public boolean isFull() {
            return size == limit;
        }
    }

    /**
     * 定长数组实现栈
     */
    public static class MyStack {

        private int[] array;

        /** 栈顶指针 */
        private int topIndex;

        /** 限制栈的大小 */
        private final int limit;

        /** 栈实际大小 */
        private int size;

        public MyStack(int limit) {
            this.limit = limit;
            array = new int[limit];
            topIndex = 0;
            size = 0;
        }

        public void push(int value) {
            if (size == limit) {
                throw new RuntimeException("栈已经满了。。。");
            }
            size++;
            array[topIndex] = value;
            topIndex++;
        }

        public int pop() {
            if (size == 0) {
                throw new RuntimeException("栈已经弹空了。。。");
            }
            size--;
            return array[--topIndex];
        }

        public boolean isEmpty() {
            return size == 0;
        }

        public boolean isFull() {
            return size == limit;
        }
    }
}
